package com.wsq.tif;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.concurrent.CountDownLatch;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.TIFFEncodeParam;

public class MultiPageRead {
	public static void main(String[] args) throws IOException,
			InterruptedException, DocumentException {
		new MultiPageRead().doitJAI();
	}
	
	public void doitJAI() throws IOException, InterruptedException,
			DocumentException {
		
		long start = System.currentTimeMillis();
		FileSeekableStream ss = new FileSeekableStream("d:/2.tif");
		TIFFDecodeParam param0 = null;
		TIFFEncodeParam param = new TIFFEncodeParam();
		ImageDecoder dec = ImageCodec.createImageDecoder("tiff", ss, param0);
		int count = dec.getNumPages();
		param.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2);
		param.setLittleEndian(false); // Intel
		System.out.println("This TIF has " + count + " image(s)");
		// FileMoveService fileMoveService=FileMoveService.getInstance();
		CountDownLatch countDownLatch = new CountDownLatch(count);
		for (int i = 0; i < count; i++) {
			Tif2pdfRunnable tif2pdfRunnable = new Tif2pdfRunnable(i,
					countDownLatch, "d:/2.tif");
			// fileMoveService.move(tif2pdfRunnable);
			Thread thread = new Thread(tif2pdfRunnable);
			thread.start();
		}
		
		countDownLatch.await();
		System.out.println(System.currentTimeMillis() - start);
		String pdfPath = "d:/tif/2.pdf";
		createPdf(pdfPath, count);
		System.out.println(System.currentTimeMillis() - start);
	}

	public void createPdf(String dest, int imageCount)
			throws MalformedURLException, IOException, DocumentException {
		Image image = Image.getInstance("d:/tif/page_1.jpg");
		Document document = new Document(image);
		PdfWriter.getInstance(document, new FileOutputStream(dest));
		document.open();
		for (int i = 1; i <= imageCount; i++) {
			image = Image.getInstance("d:/tif/page_" + i + ".jpg");
			document.setPageSize(image);
			document.newPage();
			image.setAbsolutePosition(0, 0);
			document.add(image);
		}
		document.close();

	}
}